package vip.zhenzicheng.concurrent_program.interview.alternate_output_letters;

import java.util.concurrent.CountDownLatch;

/**
 * 使用 CountDownLatch 实现指定顺序线程交替输出
 *
 * @author zhenzicheng
 * @date: 2022-06-03 13:16
 */
public class Solution_SyncWaitNotify_CountDownLatch {

  static CountDownLatch countDownLatch = new CountDownLatch(1);
  static Thread t1 = null, t2 = null;

  public static void main(String[] args) {
    char[] s1 = "123456789".toCharArray();
    char[] s2 = "abcdefghi".toCharArray();

    Object o = new Object(); // 创建一个对象用来上锁

    t1 = new Thread(() -> {
      try {
        countDownLatch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      synchronized (o) {
        for (char c : s1) {
          System.out.print(c);
          try {
            o.notify();
            o.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        o.notify(); // 必须唤醒最后一个阻塞的线程，否则将会一直wait
      }
    }, "t1");

    Thread t2 = new Thread(() -> {
      synchronized (o) {
        for (char c : s2) {
          System.out.print(c);
          countDownLatch.countDown();
          try {
            o.notify();
            o.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        o.notify();
      }
    }, "t2");

    t1.start();
    t2.start();
  }
}
